/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.elvis.music;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import android.app.Application;
import android.content.Context;
import android.widget.Toast;

import com.elvis.music.R;
import com.elvis.music.download.LrcDownLoad;
import com.elvis.music.model.Forder;
import com.elvis.music.model.LrcObject;
import com.elvis.music.model.Music;
import com.elvis.music.util.SharedPreference;

public class MusicApplication extends Application {

    private static MusicApplication instance;

    private boolean isExit;

    private boolean isPlaying;

    private Music music;

    private List<LrcObject> lrc_map;

    private int lrcCenter = 40;

    private List<Music> listMusic = new ArrayList<Music>();

    private List<Forder> sdPath;

    private LrcDownLoad lrcDownLoad;

    public static MusicApplication getInstance() {
        return instance;
    }

    public List<Music> getListMusic() {
        return listMusic;
    }

    public void setListMusic(List<Music> list) {
        listMusic = list;
    }

    public void setSdPath(List<Forder> sdPath) {
        this.sdPath = sdPath;
    }

    public List<Forder> getSdPath() {
        return this.sdPath;
    }

    public Context getContext() {
        return this;
    }

    public SharedPreference getSharedPreference() {

        return new SharedPreference(this);
    }

    public void setLrcCenter(int center) {
        lrcCenter = center;
    }

    public int getLrcCenter() {
        return lrcCenter;
    }

    public void onCreate() {
        super.onCreate();
        instance = this;
        lrc_map = new ArrayList<LrcObject>();
        initLrc(getString(R.string.app_name));
    }

    public void setIsPlaying(boolean isPlaying) {
        this.isPlaying = isPlaying;
    }

    public boolean getIsPlaying() {
        return isPlaying;
    }

    public void setPlayingMusic(Music music) {
        this.music = music;
    }

    public Music getPlayingMusic() {
        return this.music;
    }

    public List<LrcObject> getLrcMap() {
        return lrc_map;
    }

    public void setLrcMap(Music music) {
        String path = music.path.substring(0,music.path.indexOf(".")) + ".lrc";
        isExit = isLrcExit(path);
        if (!isExit) {
            initLrc(music.title);
             initLrc(getString(R.string.downing_lrc));
             lrcDownLoad = new LrcDownLoad();
             lrcDownLoad.getAndSaveLrc(this, music);
        } else {
            lrc_map.clear();
            read(path);
            if (lrc_map.size() == 0) {
                initLrc(music.title);
            }
        }

    }

    /**
     * 读取并解析lrc文件
     * 
     * @param file
     */
    public void read(String file) {
        TreeMap<Integer, LrcObject> lrc_read = new TreeMap<Integer, LrcObject>();
        String data = "";
        try {
            File saveFile = new File(file);
            FileInputStream stream = new FileInputStream(saveFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "utf8"));

            int i = 0;
            while ((data = br.readLine()) != null) {
                data = data.replace("[", "");
                data = data.replace("]", "@");

                String splistdata[] = data.split("@");
                String lrcContenet = splistdata[splistdata.length - 1];
                for (int j = 0; j < splistdata.length - 1; j++) {
                    String tmpstr = splistdata[j];
                    tmpstr = tmpstr.replace(":", ".");
                    tmpstr = tmpstr.replace(".", "@");
                    String timedata[] = tmpstr.split("@");

                    int m = Integer.parseInt(timedata[0]);
                    int s = Integer.parseInt(timedata[1]);
                    int ms = Integer.parseInt(timedata[2]);
                    int currTime = (m * 60 + s) * 1000 + ms * 10;
                    LrcObject item1 = new LrcObject();

                    item1.begintime = currTime;
                    item1.lrc = lrcContenet;
                    lrc_read.put(currTime, item1);
                    i++;
                }
            }
            stream.close();
        } catch (Exception e) {
            Toast.makeText(this, R.string.lrc_error, Toast.LENGTH_SHORT).show();
        }
        Iterator<Integer> iterator = lrc_read.keySet().iterator();
        LrcObject oldval = null;
        int i = 0;
        StringBuffer sb = new StringBuffer();
        while (iterator.hasNext()) {
            Object ob = iterator.next();
            LrcObject val = (LrcObject) lrc_read.get(ob);
            if (oldval == null)
                oldval = val;
            else {
                LrcObject item1 = new LrcObject();
                item1 = oldval;
                item1.timeline = val.begintime - oldval.begintime;
                lrc_map.add(item1);
                sb.append(String.format("[%04d]-[%04d]-%s\n", item1.begintime, item1.timeline,
                        item1.lrc));
                i++;
                oldval = val;
            }
        }
    }

    /**
     * 判断歌词文件是否存在
     * 
     * @param path
     * @return
     */
    private boolean isLrcExit(String path) {
        File file = new File(path);
        if (file.exists())
            return true;
        return false;
    }

    /**
     * 特殊情况init
     * 
     * @param message
     */
    public void initLrc(String message) {
        lrc_map.clear();
        LrcObject item = new LrcObject();
        item.lrc = message;
        item.begintime = 0;
        item.endtime = 0;
        item.timeline = 1;
        lrc_map.add(item);
    }

}
